package com.copro.chemdb.search;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.lang.ArrayUtils;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.util.Pager;

import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryListCallBack;

public class SearchUtils {

	/**
	 * Provide the query function for list
	 * 
	 * @author zozoh
	 * 
	 */
	static class ListGetter extends QueryListCallBack {

		private List<SearchResult> list;

		public ListGetter(Pager pager) {
			super(pager);
			list = new LinkedList<SearchResult>();
		}

		public List<SearchResult> getList() {
			return this.list;
		}

		@Override
		protected void makeObject(ResultSet rs) throws SQLException {
			list.add(new SearchResult(rs));
		}

	}

	public static List<SearchResult> search(Application app, int quesId,
			List<String> keywords, Pager pager, String[] subjectIds)
			throws SimpleException {
		String ids = ArrayUtils.toString(subjectIds);
		SQLSegment sql;
		if (StringUtils.len(ids) > 0) {
			sql = app.getSQL("queryLimit");
			sql.set("subjectIds", ids);
		} else {
			sql = app.getSQL("queryDefault");
		}
		sql.set("quesId", quesId);
		if (keywords.size() > 0) {
			SQLSegment kw = app.getSQL("keyword");
			for (Iterator<String> it = keywords.iterator(); it.hasNext();) {
				kw.clearAll();
				kw.set("keyword", it.next());
				sql.add("keywords", kw.toString());
				sql.add("keywords", " ");
			}
		}

		ListGetter callback = new ListGetter(pager);
		app.query(sql.toString(), callback);

		return callback.getList();
	}
}
